<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>管理员信息</title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/vue.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap-table.min.css">
    <script src="js/bootstrap-table.min.js"></script>
    <script src="js/bootstrap-table-zh-CN.min.js"></script>
    <script type="text/javascript" src="js/layui.min.js"></script>
    <link rel="stylesheet" href="css/layui.min.css"/>
    <link href="css/bootstrap-switch.min.css" rel="stylesheet">
    <script src="js/bootstrap-switch.min.js"></script>
</head>
<body>
<div class="container-fluid" id="app">
    <div id="toolbar" class="btn-group">
<!--        <button id="btn_see" type="button" class="btn btn-primary btn-sm"  @click="seePermissionInfo">-->
<!--            <span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span>查看权限-->
<!--        </button>-->
        <button id="btn_add" type="button" class="btn btn-success btn-sm" data-toggle="modal"
                data-target="#myModal" @click="openModel">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
        <button id="btn_edit" type="button" class="btn btn-info btn-sm" @click="findAdmin">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
        </button>
        <button id="btn_delete" type="button" class="btn btn-danger btn-sm" @click="deleteAdmin">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
        </button>
    </div>
    <!--Modal模态框 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">新增管理员</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-3 control-label">登录名</label>
                            <div class="col-sm-5">
                                <input v-model="loginName" type="text" class="form-control"
                                       placeholder="请输入登录名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">密　码</label>
                            <div class="col-sm-5">
                                <input v-model="password" type="password" class="form-control"
                                       placeholder="请输入密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">权　限</label>
                            <div class="col-sm-5">
                                <div id="tree1" style="background: #f5f5f5;padding-bottom: 10px;"></div>
<!--                                <input v-model="password" type="password" class="form-control"-->
<!--                                       placeholder="请输入密码">-->
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button v-if="isUpdate" type="button" class="btn btn-primary" @click="updateAdmin" data-dismiss="modal">修改</button>
                    <button v-else type="button" class="btn btn-primary" @click="addAdmin" data-dismiss="modal">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!--Modal模态框 查看权限-->
    <div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel2">权限信息</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-3 control-label">权　限</label>
                            <div class="col-sm-5">
                                <div id="tree2" style="background: #f5f5f5;padding-bottom: 10px;"></div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!--    bootstrap-table-->
    <table id="table"></table>
</div>
</body>
<script>
    var vue = new Vue({
        el:'#app',
        data:{
            loginName:'',
            password:'',
            isUpdate:false,
            select:[]
        },
        created:function () {
            this.getTreeData()
        },
        methods:{
            openModel:function () {
                this.isUpdate=false
                this.loginName = ''
                this.password = ''
                this.getTreeData()
            },
            addAdmin:function () {
                var ids = this.getTreeSelect()
                axios.post('adminInfo/insert',{
                    "adminName":this.loginName,
                    "adminPwd":this.password,
                    "permissions":ids
                }).then((response)=>{
                    if (response.data.code=='1'){
                        $("#table").bootstrapTable('refresh');
                        layer.msg('添加成功', {offset: '100px', icon: 1});
                    }else {
                        layer.msg('添加失败', {offset: '100px', icon: 2});
                    }
                })
            },
            deleteAdmin:function () {
                var selectData = $("#table").bootstrapTable('getSelections')
                if (selectData != null && selectData.length > 0) {
                    var index = layer.confirm('是否删除改记录？', {
                        offset: '100px',
                        title: '删除提示',
                        icon: 3,
                        btn: ['取消', '删除',] //可以无限个按钮
                    }, function () {
                        layer.close(index)
                    }, function () {
                        axios.delete('adminInfo/delete/' + selectData[0].id).then((response) => {
                            $("#table").bootstrapTable('refresh');
                            layer.msg('删除成功', {offset: '100px', icon: 1});
                        })
                        selectData = null
                    });
                } else {
                    layer.msg('当前无选择记录', {offset: '100px', icon: 2});
                }
            },
            updateAdmin:function () {
                var ids = this.getTreeSelect()
                var selectData = $("#table").bootstrapTable('getSelections')
                axios.put('adminInfo/update',{
                    "id":selectData[0].id,
                    "adminName":this.loginName,
                    "adminPwd":this.password,
                    "permissions":ids
                }).then((response) => {
                    $("#table").bootstrapTable('refresh');
                    this.isUpdate = false
                    layer.msg('修改成功', {offset: '100px', icon: 1});
                })
            },
            findAdmin:function () {
                var selectData = $("#table").bootstrapTable('getSelections')
                if (selectData != null && selectData.length > 0) {
                    this.isUpdate = true
                    $('#myModal').modal('show')
                    axios.get('adminInfo/query/'+selectData[0].id).then((response) => {
                        var permissions = response.data.data.permissions
                        var ids = []
                        for (let i = 0; i < permissions.length; i++) {
                            ids.push(permissions[i].fid)
                        }
                        layui.use('tree', function() {
                            var tree = layui.tree;
                            tree.setChecked('demoId1', ids);
                        })
                        if (response.data.code=='1'){
                            this.loginName = response.data.data.adminName
                            this.password = response.data.data.adminPwd
                            // console.log(response.data.date.adminPwd)
                        }
                    })
                } else {
                    layer.msg('当前无选择记录', {offset: '100px', icon: 2});
                }
            },
            getTreeData:function () {
                layui.use('tree', function(){
                    var tree = layui.tree;
                    // 后取后台数据
                    axios.get('functionMenu/queryAllForTree').then((response)=> {
                        if (response.data.code==='0'){
                            alert(response.data.msg)
                        }else {
                            //渲染
                            var inst1 = tree.render({
                                elem: '#tree1', //绑定元素
                                // edit:['add','update', 'del'],
                                id: 'demoId1',
                                data: response.data.data,
                                showCheckbox:true,
                            });
                            var inst2 = tree.render({
                                elem: '#tree2', //绑定元素
                                // edit:['add','update', 'del'],
                                id: 'demoId2',
                                data: response.data.data,
                                showCheckbox:true,
                                disabled:false
                            });
                        }
                    })

                })
            },
            getTreeSelect:function () {
                var idList=[]//节点的id
                layui.use('tree', function(){
                    var tree = layui.tree;
                    //获得选中的节点
                    var checkData = tree.getChecked('demoId1');
                    for (i=0;i<checkData.length;i++){
                        var e = {fid:checkData[i].id}
                        idList.push(e)
                        var child = checkData[i].children
                        for (j=0;j<child.length;j++){
                            var e = {fid:child[j].id}
                            idList.push(e)
                        }
                    }
                })
                return idList
            },
            seePermissionInfo:function () {
                var selectData = $("#table").bootstrapTable('getSelections')
                if (selectData != null && selectData.length > 0) {
                    $('#myModal2').modal('show')
                    axios.get('adminInfo/query/'+selectData[0].id).then((response) => {
                        var permissions = response.data.data.permissions
                        var ids = []
                        for (let i = 0; i < permissions.length; i++) {
                            ids.push(permissions[i].fid)
                        }
                        layui.use('tree', function() {
                            var tree = layui.tree;
                            tree.setChecked('demoId2', ids);
                        })
                    })
                } else {
                    layer.msg('当前无选择记录', {offset: '100px', icon: 2});
                }
            }
        }
    })

    //设置table属性
    $('#table').bootstrapTable({
        url: 'adminInfo/queryAll',
        method: "get",
        pagination: false, //启动分页
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        showColumns: true,                  //是否显示所有的列
        showRefresh: true,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        height: 710,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
        onLoadSuccess: function () {  //加载成功时执行
            //初始化开关按钮
            initSwitch()
            //复选框水平垂直居中显示
            $(".bs-checkbox").css({'text-align': 'center', 'vertical-align': 'middle'})
            $(".bootstrap-switch").css({'border-radius': '20px'})

        },
        onLoadError: function () {  //加载失败时执行
            // layer.msg("加载数据失败", {time : 1500, icon : 2});
            // alert("加载数据失败")
        },
        //设置列属性
        columns: [{
            checkbox: true,
            visible: true,
        }, {
            title: '序号',
            width: 40,
            align: "center",
            valign: 'middle',
            formatter: function (value, row, index) {
                var pageSize = $('#table').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                var pageNumber = $('#table').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
            }
        }, {
            field: 'id',
            title: 'id',
            align: "center",
            valign: 'middle',
        }, {
            field: 'adminName',
            title: '登录名',
            align: "center",
            valign: 'middle',
        },{
            field: 'status',
            title: '状态',
            align: "center",
            valign: 'middle',
            formatter: function (value, row, index) {
                var a=row.id
                if(row.status=='1'){
                    return '<input value="'+a+'" type="checkbox" name="my-checkbox1" checked>';
                }else if(row.status=='0'){
                    return '<input value="'+a+'" type="checkbox" name="my-checkbox1" check>';
                }
            }
        },{
            field: 'createTime',
            title: '创建时间',
            align: "center",
            valign: 'middle',
        }]
    })

    function search() {
        $('#table').bootstrapTable('refresh');
    }
    function fresh() {
        setTimeout(() => {$('#table').bootstrapTable('refresh');},1)
    }

    function initSwitch(){
        $('[name="my-checkbox1"]').bootstrapSwitch({
            onText : "on",      // 设置ON文本
            offText : "off",    // 设置OFF文本
            onColor : "success",// 设置ON文本颜色(info/success/warning/danger/primary)
            offColor : "danger",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
            size : "mini",    // 设置控件大小,从小到大  (mini/small/normal/large)
            // 当开关状态改变时触发
            onSwitchChange:function(event,state){
                if(state==true){//打开
                    axios.put('adminInfo/updateStatus/'+this.value+'/1').then((response)=>{})
                }else{//关闭
                    axios.put('adminInfo/updateStatus/'+this.value+'/0').then((response)=>{})
                }
            }
        })
    }
    //关闭模态框回调函数
    $('#myModal').on('hidden.bs.modal', function (e) {
        vue.getTreeData()
    })
</script>
</html>